import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/myreq")
public class MyReqServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder sb=new StringBuilder();
        //得到请求的协议和版本号
        sb.append("协议："+req.getProtocol()+"<br>");
        //得到请求的方法
        sb.append("方法:"+req.getMethod()+"<br>");
        //得到URI
        sb.append("URI:"+req.getRequestURI()+"<br>");
        sb.append("URL:"+req.getRequestURL()+"<br>");
        //获取上下文路径
        sb.append("contextPath:"+req.getContextPath()+"<br>");
        //获取URL中的查询字符串
        sb.append("QueryString:"+req.getQueryString()+"<br>");

        //获取所有参数的名称和内容
//        sb.append("<hr><h1>所有参数</h1>");
//        Enumeration<String> parameterNames=req.getParameterNames();
//        while(parameterNames.hasMoreElements()){
//            String parameterName=parameterNames.nextElement();
//            String parameterValue=req.getParameter(parameterName);
//            sb.append(parameterName+" "+":"+parameterValue+"<br>");
//        }

        //获取所有请求头名称和请求头的内容
        sb.append("<hr><h1>请求头</h1>");
        Enumeration<String> headNames=req.getHeaderNames();
        while(headNames.hasMoreElements()){
            String headName=headNames.nextElement();
            String headValue=req.getHeader(headName);
            sb.append(headName+" "+":"+headValue+"<br>");
        }
        sb.append("<hr>");
        sb.append("参数："+req.getParameter("username")+"<br>");

        //获取请求主体的长度
        sb.append("请求长度："+req.getContentLength());
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(sb.toString());
    }
}
